<?php
namespace app\api\model\foodcash;

use app\common\model\Goods as GoodsModel;
use app\api\model\GoodsSpec;
use think\facade\Db;

/**
 * 商品模型
 */
class Goods extends GoodsModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [];
    
    /**
     * 按照分类获取上架的所有商品
     */
	public function foodGoodsList($shop_id, $category, $user_id)
	{
		//获取当前购物车商品
		$cart = new Cart($user_id,$shop_id);
		$cart_data = $cart->getCart();
		$cartlist = $cart->getList();
		$list=array();
		for($i=0;$i<sizeof($category);$i++){
			$deail = $this->with(['spec', 'image.file', 'spec_rel.spec'])
						->where([
							'goods_status' => 10, 
							'category_id' => $category[$i]['category_id'],
							'shop_id' => $shop_id
						])
						->order(['goods_sort', 'goods_id' => 'desc'])
						->select();
			$goods = $deail;
			$count = 0;//该分类在购物车中的数量
			// 规格信息
			for($n=0;$n<sizeof($goods);$n++){
				$goods[$n]['total_num'] = 0;//购物车数量
				if($goods[$n]['spec_type'] == 20){
					$goods[$n]['specData'] = get_many_spec_data($goods[$n]['spec_rel'], $goods[$n]['spec']);
					for($s=0;$s<sizeof($goods[$n]['spec']);$s++){
						$goods[$n]['spec'][$s]['sell_num'] = 0;
						if(isset($cart_data[$goods[$n]['goods_id'].'_'.$goods[$n]['spec'][$s]['spec_sku_id']])){
							$goods[$n]['total_num'] = $goods[$n]['total_num'] + $cart_data[$goods[$n]['goods_id'].'_'.$goods[$n]['spec'][$s]['spec_sku_id']]['goods_num'];	
							$goods[$n]['spec'][$s]['sell_num'] = $cart_data[$goods[$n]['goods_id'].'_'.$goods[$n]['spec'][$s]['spec_sku_id']]['goods_num'];
							$count++;
						}
					}
				}else{
					if(isset($cart_data[$goods[$n]['goods_id'].'_'])){
						$goods[$n]['total_num'] = $cart_data[$goods[$n]['goods_id'].'_']['goods_num'];	
						$count++;
					}
					$goods[$n]['specData'] = null;
				}
			}
			$category[$i]['count'] = $count;//该分类在购物车中的数量
			$category[$i]['goods'] = $goods;
		}
		return compact('category','cartlist');
	}
	
	
	/**
     * 按照分类获取上架的所有商品
     */
	public function getGoodsList($shop_id,$category)
	{
		$list=array();
		for($i=0;$i<sizeof($category);$i++){
			$goods = $this->with(['spec', 'image.file', 'spec_rel.spec'])
						->where([
							'category_id' => $category[$i]['category_id'],
							'shop_id' => $shop_id
						])
						->order(['goods_sort', 'goods_id' => 'desc'])
						->select();
			// 规格信息
			for($n=0;$n<sizeof($goods);$n++){
				if($goods[$n]['spec_type'] == 20){
					$goods[$n]['specData'] = get_many_spec_data($goods[$n]['spec_rel'], $goods[$n]['spec']);
				}else{
					$goods[$n]['specData'] = null;
				}
			}
			$category[$i]['goods'] = $goods;
		}
		return $category;
	}

	
	/**
     * 编辑
     */
    public function add($data,$shop_id)
    {
    	$data = json_decode($data,true);
    	if (!isset($data['images']) || empty($data['images'])) {
            $this->error = '请上传商品图片';
            return false;
        }
    	if(empty($data['category_id'])) {
			$this->error = '请设置商品分类';
            return false;
		}
		if(empty($data['goods_name'])) {
			$this->error = '商品名称不可为空';
            return false;
		}
		if($data['spec_type'] == 10){
			if (empty($data['spec']['goods_price'])) {
				$this->error = '商品价格不可为空';
                return false;
			}
		}else{
			foreach ($data['spec_many']['spec_list'] as $item){
			    if(empty($item['form']['goods_price'])){
			        $this->error = '商品价格不可为空';
                    return false;  
			    }
			}
		}
		if(empty($data['goods_sort'])) {
			$this->error = '商品显示排序号不可为空';
            return false;
		}
		$data['shop_id'] = $shop_id;
        $data['content'] = isset($data['content']) ? $data['content'] : '';
        $data['applet_id'] = $data['spec']['applet_id'] = self::$applet_id;
        // 开启事务
        Db::startTrans();
        try {
            // 保存商品
            $this->save($data);
            $this->addGoodsImages($data['images']);
             // 添加规格数据
            if ($data['spec_type'] == '10') {
                $this->spec()->save($data['spec']);// 单规格
            } elseif($data['spec_type'] == '20') {
                $model = new GoodsSpec;
                // 添加商品与规格关系记录
                $model->addGoodsSpecRel($this['goods_id'], $data['spec_many']['spec_attr']);
                // 添加商品sku
                $model->addSkuList($this['goods_id'], $data['spec_many']['spec_list']);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

	/**
     * 编辑
     */
    public function edit($data)
    {
    	$data = json_decode($data,true);
    	if (!isset($data['images']) || empty($data['images'])) {
            $this->error = '请上传商品图片';
            return false;
        }
    	if(empty($data['category_id'])) {
			$this->error = '请设置商品分类';
            return false;
		}
		if(empty($data['goods_name'])) {
			$this->error = '商品名称不可为空';
            return false;
		}
		if($data['spec_type'] == 10){
			if (empty($data['spec']['goods_price'])) {
				$this->error = '商品价格不可为空';
                return false;
			}
		}else{
			foreach ($data['spec'] as $item){
			    if(empty($item['form']['goods_price'])){
			        $this->error = '商品价格不可为空';
                    return false;  
			    }
			}
		}
		if(empty($data['goods_sort'])) {
			$this->error = '商品显示排序号不可为空';
            return false;
		}
        // 开启事务
        Db::startTrans();
        try {
            // 保存商品
            $this->save($data);
            $this->addGoodsImages($data['images']);
            // 商品规格
            if($data['spec_type'] == 10){
            	$spec = GoodsSpec::get($data['spec']['goods_spec_id']);
            	$spec->save($data['spec']);
            }else{
            	foreach ($data['spec'] as $item) {
            		$spec = GoodsSpec::get($item['goods_spec_id']);
            		$spec->save([
            			'goods_price' => $item['form']['goods_price'],
            			'line_price' => $item['form']['line_price']
            		]);
            	}
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }
    
    /**
     * 添加商品图片
     */
    private function addGoodsImages(array $images)
    {
        $this->image()->delete();
        $data = array_map(function ($image_id) {
            return [
                'image_id' => $image_id,
                'applet_id' => self::$applet_id
            ];
        }, $images);
        return $this->image()->saveAll($data);
    }

    /**
     * 商品详情：HTML实体转换回普通字符
     */
    public function getContentAttr($value)
    {
       return htmlspecialchars_decode($value);
    }

    /**
     * 根据商品id集获取商品列表 (购物车列表用)
     */
    public function getListByIds($goodsIds) {
        return $this->with(['category','image.file', 'spec','spec.image','spec_rel.spec'])
            ->where('goods_id', 'in', $goodsIds)->select();
    }

}
